<template>
  <div class="formChekbox">
    <el-form-item :label="title + '：'">
      <el-checkbox-group v-model="from">
        <el-checkbox
          v-for="item in fromtypelist"
          :label="item.id"
          :key="item.lable"
          @change="handleValue(item)"
        >
          {{ item.lable }}
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'formChekbox',
  props: {
    title: {
      type: String,
      default: '关键词'
    },
    fromlist: {
      type: Array,
      default: () => {}
    },
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      from: [],
      fromNode: [],
      fromtypelist: [] // 获取来源类型
    }
  },
  methods: {
    // 获取获取来源类型的树形结构list
    getfromtopeList() {
      let _this = this
      this.$axios
        .get('/getSourceTypeTreeBeanList?category=1')
        .then(res => {
          if (res.status) {
            let result = res.data.result
            if (Object.prototype.toString.call(result) === '[object Array]') {
              let index = result.findIndex(item => item.lable === 'APP采集')
              let index1 = result.findIndex(item => item.lable === '未知来源')
              let obj = result.find(item => item.lable === '未知来源')
              result[index].lable = 'APP'
              result.splice(index, 1, result[index])
              result.splice(index1, 1)
              result.push(obj)
              _this.fromtypelist = result
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleValue(data) {
      this.fromNode = []
      for (let j in this.from) {
        for (let i in this.fromtypelist) {
          if (this.from[j] === this.fromtypelist[i].id) {
            this.fromNode.push(this.fromtypelist[i].lable)
            break
          }
        }
      }
      let params
      switch (this.type) {
        case '1':
          params = { from: this.from, fromNode: this.fromNode }
          break
        case '7':
          params = { type: this.from, typeNode: this.fromNode }
          break
      }
      this.setNewFormData(params)
    },
    ...mapMutations('charts', ['setNewFormData'])
  },
  computed: {
    ...mapState('charts', ['formData', 'chartsCondition', 'resetFormData'])
  },
  mounted() {
    switch (this.type) {
      case '1':
        this.from = this.formData.from
        this.getfromtopeList()
        break
      case '7':
        this.from = this.formData.type
        this.fromtypelist = this.fromlist
        break
    }
  },
  watch: {
    resetFormData() {
      switch (this.type) {
        case '1':
          this.from = this.formData.from
          break
        case '7':
          this.from = this.formData.type
          break
      }
    }
  }
}
</script>

<style scoped></style>
